import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getAccessToken } from '@/utils/auth'
import { isFileStream } from '@/utils'
import router from '../router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: process.env.VUE_APP_REQUEST_TIMEOUT // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = 'Bearer ' + getAccessToken()
    }
    console.log('request:', config)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
/**
 * Response interceptor
 *
 * If you want to get http information such as headers or status
 * Please return  response => response
 *
 * Determine the request status by custom code
 * Here is just an example
 * You can also judge the status by HTTP Status Code
 */
service.interceptors.response.use(
  response => {
    console.log('_Axios Response:', response.request.responseURL)
    const headers = response.headers
    const res = response.data
    if (typeof res === 'string' && res) {
      console.log('_Axios res string:', response)
      return {
        data: res,
        headers: headers
      }
    } else if (isFileStream(res)) {
      console.log(headers['content-type'].indexOf('application/json') !== -1)
      console.log(response.type)
      console.log('_Axios res stream:', response)
      return {
        data: res,
        headers: headers
      }
    }
    console.log('_Axios res response:', response)
    if (res.code === 200) {
      return res
    }
    if (res.code === 401 || res.code === 402) {
      MessageBox.confirm('系统登录已过期，可以取消以停留在此页面或重新登录 ', 'Confirm logout', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    } else if (res.code === 403) {
      MessageBox.confirm(
        '您可能没有该功能或资源的操作权限，请与管理员联系以查明您是否有访问权限。',
        res.msg || '访问受限',
        {
          confirmButtonText: '确定',
          type: 'warning',
          iconClass: 'em-icon-authority',
          showCancelButton: false,
          closeOnClickModal: false,
          showClose: false,
          center: true
        }
      )
        .then(() => {
          console.log('qued')
          // router.go(-1)
        })
        .catch(() => {
          router.go(-1)
        })
    } else if (res.code === 429) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
    }
    console.log('_Axios Response Error:', response) // for debug
    return Promise.reject(new Error(res.msg || 'Error'))
  },
  error => {
    // console.log('_Axios Response Error:', error) // for debug
    // console.log(error) // for debug
    // console.log(error.code, error.name, error.message, error.response)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Boolean} loading [是否显示加载]
 */
export function get(url, params, fastmode = true) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'GET',
      params
    })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        console.log('[Promise get Error]', err)
        reject(err)
      })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Boolean} fastmode [请求时携带的参数]
 * @param {Object} config [请求时携带的参数]
 */
export function post(url, params, config) {
  return new Promise((resolve, reject) => {
    // console.log(url, params, config)
    const headers = Object.assign({}, config)
    service
      .post(url, params, {
        headers: headers
      })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        console.log('[POST reject Error]', err)
        reject(err)
      })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Boolean} fastmode [请求时携带的参数]
 * @param {Object} config [请求时携带的参数]
 */
export function stream(url, params, config) {
  return new Promise((resolve, reject) => {
    // console.log(url, params, config)
    const headers = Object.assign({}, config)
    service
      .post(url, params, {
        headers: headers,
        responseType: 'arraybuffer',
        timeout: process.env.VUE_APP_REQUEST_TIMEOUT * 2
      })
      .then(res => {
        console.log('res', res)
        console.log(res.headers['content-type'].indexOf('application/json') !== -1)
        if (res.headers['content-type'].indexOf('application/json') !== -1) {
          var blob = new Blob([res.data])
          const reader = new FileReader()
          reader.readAsText(blob)
          reader.onload = e => {
            const readerres = reader.result
            let parseObj = {}
            parseObj = JSON.parse(readerres)
            console.log('resparseObj', parseObj)
            reject(parseObj)
          }
        } else {
          resolve(res)
        }
      })
      .catch(err => {
        console.log('[POST reject Error]', err)
        reject(err)
      })
  })
}

export default service
